//
//  packagerForIOS.m
//  AutoCompiler_Script
//
//  Created by Vescky on 13-5-16.
//  Copyright (c) 2013年 Vescky. All rights reserved.
//

#import "packagerForIOS.h"
#import "PathParser.h"
#import "DataInfo.h"
#import "AppsProjectInfoParser.h"
#import "NSImage+Resize.h"
#import "FileOperator.h"

#define TOTAL_ICONS 4

@implementation packagerForIOS {
    int iosIconDone;
}

@synthesize delegate;

packagerForIOS *pkgIOS;

bool isLoadingIconsComplete;

+ (id)sharePackagerForIOS {
    if (!pkgIOS) {
        pkgIOS = [[packagerForIOS alloc] init];
    }
    return pkgIOS;
}

//- (void)autoRunWithAppBundleID:(NSString*)appEnName {
//    appsImageEngineIOS = [AppsImageEngine sharedEngine];
//    appsImageEngineIOS.delegate = self;
//    proInfo =  [AppsProjectInfoParser parseProjectInfo];
//    PathParser *pp = [PathParser sharePathParser];
//    if ([self initIOSWorkSpace]) {
//        [self parseBundle];
//        [self pickFiles];
//        [self ModifyAppInfoWithAppCNName:proInfo.appsName AppENName:appEnName deploymentSDKVersion:pp.deploymentSdkVersion AppVersion:proInfo.version ProjectPath:pp.outIosProjectPath];
//        //下载完icons后调用compile的函数
//        int i = 0;
//        while (1) {
//            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//            [NSThread sleepForTimeInterval:1.0];
//            if (isLoadingIconsComplete || i >= 90) {
//                isLoadingIconsComplete = NO;
//                [self compileWithLogsFiles:NO appName:appEnName];
//                break;
//            }
//            i++;
//        }
//    }
//}
//
//- (void)autoCompileIOS:(NSString*)enName environment:(NSString*)environment createLogFile:(bool)isLogfile {
//    appsImageEngineIOS = [AppsImageEngine sharedEngine];
//    appsImageEngineIOS.delegate = self;
//    proInfo =  [AppsProjectInfoParser parseProjectInfo];
//    PathParser *pp = [PathParser sharePathParser];
//    if ([self initIOSWorkSpace]) {
//        [self parseBundle];
//        [self pickFiles];
//        [self ModifyAppInfoWithAppCNName:proInfo.appsName AppENName:enName deploymentSDKVersion:pp.deploymentSdkVersion AppVersion:proInfo.version ProjectPath:pp.outIosProjectPath];
//        [self ModifyServerIP:environment]; //修改ip地址
//        //下载完icons后调用compile的函数
//        int i = 0;
//        while (i < 100) {
//            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//            [NSThread sleepForTimeInterval:1.0];
//            NSLog(@"waiting for image download:%ds\n",i);
//            if (isLoadingIconsComplete || i >= 90) {
//                isLoadingIconsComplete = NO;
////                [self compileWithLogsFiles:isLogfile];
//                break;
//            }
//            i++;
//        }
//    }
//
//}

//通过dictionary穿参数  -------  目前为止的最新调用方法 2013.10 --------
- (void)autoCompileIOSWithContent:(NSMutableDictionary*)content {
    appsImageEngineIOS = [AppsImageEngine sharedEngine];
    appsImageEngineIOS.delegate = self;
    proInfo =  [AppsProjectInfoParser parseProjectInfo];
    PathParser *pp = [PathParser sharePathParser];
    
    NSString *enName = [content objectForKey:@"enname"];
    NSString *environment = [content objectForKey:@"environment"];
    NSString *cPath = [content objectForKey:@"identity"];
    NSString *buildFlag = [content objectForKey:@"build"];
    NSString *isLogfile = [content objectForKey:@"save"];
    NSString *xmppIp = [content objectForKey:@"xmppIp"];
    NSString *appType = [content objectForKey:@"appType"];
    NSString *mode = [content objectForKey:@"mode"];//0普通app，1商圈Publish，2商圈Preview
    
    if ([self initIOSWorkSpace]) {
        [self parseBundle];
        
        if ([mode intValue] == 0) {
            [self pickFiles];
            
        }
        else {
            NSLog(@"\n\n------ not normal template,do not delete any file!  ------\n\n\n");
        }
        
        [self ModifyAppInfoWithAppCNName:proInfo.appsName AppENName:enName deploymentSDKVersion:pp.deploymentSdkVersion AppVersion:proInfo.version ProjectPath:pp.outIosProjectPath];
        [self ModifyServerIP:environment withMode:mode]; //修改ip地址
        [self ModifyXmppIp:xmppIp];
        
        cPath = [self detectProfiles];
        
        if (cPath && cPath.length > 1) {
            [Modify_pbxproj modifyMobileProvision:pp.outIosProjectPath profilePath:cPath];//修改证书
        }
        else {
            [Modify_pbxproj modifyBundleID:[NSString stringWithFormat:@"%@.%@",pp.appBundleIdHeadString,enName] projectPath:pp.outIosProjectPath];
        }
        
        //下载完icons后调用compile的函数
        int i = 0;
        while (i < 100) {
//            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            [NSThread sleepForTimeInterval:1.0];
            NSLog(@"waiting for image download:%ds\n",i);
            if (isLoadingIconsComplete || i >= 90) {
                isLoadingIconsComplete = NO;
                if (buildFlag && [buildFlag isEqualToString:@"YES"]) {
                    bool flag = NO;
                    if (isLogfile && [isLogfile isEqualToString:@"YES"]) {
                        flag = YES;
                    }
                    [self compileWithLogsFiles:flag appName:enName];
                }
                break;
            }
            i++;
        }
    }
}

- (NSString*)detectProfiles {
    
    return @"/usr/local/autocompiler/resources/longpush3Development.mobileprovision";
    
    NSLog(@"########### detecting profiles.... #############");
    PathParser *pp = [PathParser sharePathParser];
    NSString *iosFolder = [pp.outIosProjectPath stringByDeletingLastPathComponent];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *arr = [fm contentsOfDirectoryAtPath:iosFolder error:nil];
    for (int i = 0; i < [arr count]; i++) {
        NSString *fName = [arr objectAtIndex:i];
        NSLog(@"########### detecting profiles:%@/%@ #############",iosFolder,fName);
        if ([[[fName pathExtension] lowercaseString] isEqualToString:@"zip"]) {
            //has profiles
            NSLog(@"########### found a zip file:%@/%@ #############",iosFolder,fName);
            NSString *unzipCmd = [NSString stringWithFormat:@"cd %@\n unzip -o %@\n",iosFolder,fName];
            NSLog(@"########### unzip it:\n%@ #############",unzipCmd);
            system([unzipCmd UTF8String]);
            
            NSString *certPath = [iosFolder stringByAppendingPathComponent:[fName stringByDeletingPathExtension]];
            NSArray *arr1 = [fm contentsOfDirectoryAtPath:iosFolder error:nil];
            for (int j = 0; j < [arr1 count]; j++) {
                NSString *itemPath = [iosFolder stringByAppendingPathComponent:[arr1 objectAtIndex:j]];
                BOOL isDir = NO;
                if ([fm fileExistsAtPath:itemPath isDirectory:&isDir]) {
                    if (isDir && ![[itemPath lastPathComponent] isEqualToString:@"AppsTemplate"]) {
                        certPath = itemPath;
                    }
                }
            }
            NSLog(@"########### certs path:%@ #############",certPath);
            //find ad-hoc profile
            NSArray *profilesArr = [fm contentsOfDirectoryAtPath:certPath error:nil];
            for (int j = 0; j < [profilesArr count]; j++) {
                NSString *profileName = [profilesArr objectAtIndex:j];
                NSLog(@"########### comparing profile:%@ #############",profileName);
                if ([[profileName lowercaseString] stringByMatching:@"adhoc"] || [[profileName lowercaseString] stringByMatching:@"achoc"]
                    || [[profileName lowercaseString] stringByMatching:@"inhouse"]) {
                    NSLog(@"########### found profile:%@ #############",[certPath stringByAppendingPathComponent:profileName]);
                    return [certPath stringByAppendingPathComponent:profileName];
                }
            }
        }
    }
    return nil;
}

//复制Launch Images  --- Default-568h@2x --  Default  --  Default@2x
- (void)prepareLaunchImages {
    PathParser *pp = [PathParser sharePathParser];
    NSString *resourcesPath = [NSString stringWithFormat:@"%@/%@/Resources",pp.outIosProjectPath,pp.templateProjectName];
    NSFileManager *fm = [NSFileManager defaultManager];
    DataInfo *dataInfo = [AppsProjectInfoParser parseDataInfo];
    
    if (dataInfo.OthersStartPic && dataInfo.OthersStartPic.length > 0) {
        NSString *normalPath = [NSString stringWithFormat:@"%@/www/%@",pp.incomeBundlePath,dataInfo.OthersStartPic];
        BOOL isDir = YES;
         if (![fm fileExistsAtPath:normalPath isDirectory:&isDir]) {
             return;
         }
        if (!isDir) {
            if ([fm fileExistsAtPath:[resourcesPath stringByAppendingPathComponent:@"Default.png"]]) {
                [fm removeItemAtPath:[resourcesPath stringByAppendingPathComponent:@"Default.png"] error:nil];
            }
            [fm copyItemAtPath:normalPath toPath:[resourcesPath stringByAppendingPathComponent:@"Default.png"] error:nil];
            
            if ([fm fileExistsAtPath:[resourcesPath stringByAppendingPathComponent:@"Default@2x.png"]]) {
                [fm removeItemAtPath:[resourcesPath stringByAppendingPathComponent:@"Default@2x.png"] error:nil];
            }
            [fm copyItemAtPath:normalPath toPath:[resourcesPath stringByAppendingPathComponent:@"Default@2x.png"] error:nil];
        }
    }
    
    if (dataInfo.Iphone5StartPic && dataInfo.Iphone5StartPic.length > 0) {
        NSString *forip5Path = [NSString stringWithFormat:@"%@/www/%@",pp.incomeBundlePath,dataInfo.Iphone5StartPic];
        BOOL isDir = YES;
        if (![fm fileExistsAtPath:forip5Path isDirectory:&isDir]) {
            return;
        }
        if (!isDir) {
            if ([fm fileExistsAtPath:[resourcesPath stringByAppendingPathComponent:@"Default-568h@2x.png"]]) {
                [fm removeItemAtPath:[resourcesPath stringByAppendingPathComponent:@"Default-568h@2x.png"] error:nil];
            }
            [fm copyItemAtPath:forip5Path toPath:[resourcesPath stringByAppendingPathComponent:@"Default-568h@2x.png"] error:nil];
        }
    }
}

#pragma mark - 第1步--初始化
- (bool)initIOSWorkSpace {
    NSLog(@">>>>>>>>>>>>>>>>>>>IOS: Initializing work space,it takes about 1 min... <<<<<<<<<<<<<<<<<<<<<<\n");
    return [Modify_pbxproj initWorkSpaceWithMode:NO];
}

#pragma mark - 第2步--解析zip包中的信息
//解析zip包中的信息
- (void)parseBundle {
    NSLog(@">>>>>>>>>>>>>>>>>>>IOS: Parsing zip package,i takes about 30s... <<<<<<<<<<<<<<<<<<<<<\n");
    //替换bundle
    PathParser *pp = [PathParser sharePathParser];
    NSString *resourcesPath = [NSString stringWithFormat:@"%@/%@/Resources",pp.outIosProjectPath,pp.templateProjectName];
   
    isLoadingIconsComplete = NO;
    FileOperator *fop = [FileOperator shareFileOperator];
    NSString *bigIconPath = [fop getIconPathFromZip];
    if (bigIconPath) {
        NSImage *bigIcon = [NSImage imageNamed:bigIconPath];
        if (bigIcon) {
            [self saveIconWithLocalIconImage:bigIcon];
            isLoadingIconsComplete = YES;
        }
    }
    
    //本地无图片，从server获取icon
    if (!isLoadingIconsComplete) {
        if (proInfo.icon && proInfo.icon.length > 0) {
            NSString *iconName = [proInfo.icon stringByReplacingOccurrencesOfString:@".png" withString:@""];
//            [appsImageEngineIOS makeAppIconWithImageUrl:iconName saveAtPath:resourcesPath];
            [self loadIOSIconsUsingGCDWithImageUrl:iconName projectPath:resourcesPath];
        }
        else {
            //替换app-icon
            [FileOperator replaceFile:[NSString stringWithFormat:@"%@/%@/Resources/icon.png",pp.outIosProjectPath,pp.templateProjectName] withNewFile:[NSString stringWithFormat:@"%@/defaultAppIcon/icon.png",pp.workSpaceFolderPath]];
            [FileOperator replaceFile:[NSString stringWithFormat:@"%@/%@/Resources/icon@2x.png",pp.outIosProjectPath,pp.templateProjectName] withNewFile:[NSString stringWithFormat:@"%@/defaultAppIcon/icon@2x.png",pp.workSpaceFolderPath]];
            [FileOperator replaceFile:[NSString stringWithFormat:@"%@/%@/Resources/icon_ios7.png",pp.outIosProjectPath,pp.templateProjectName] withNewFile:[NSString stringWithFormat:@"%@/defaultAppIcon/iconicon_ios7.png",pp.workSpaceFolderPath]];
            isLoadingIconsComplete = YES;
        }
    }
    
    
    //准备Launch Images
    [self prepareLaunchImages];
    
    [FileOperator replaceFile:[NSString stringWithFormat:@"%@/%@/%@",pp.outIosProjectPath,pp.templateProjectName,pp.incomeBundleName] withNewFile:pp.incomeBundlePath];
    
    NSMutableArray *viewName = [[NSMutableArray alloc] init];
    NSMutableArray *viewLayout = [[NSMutableArray alloc] init];
    DataInfo *dInfo = [AppsProjectInfoParser parseDataInfo];
    
    HomePageDataListItem *hpItem = [dInfo.dataList objectAtIndex:1];
    if (hpItem.sysTabName) {
        [viewName addObject:hpItem.sysTabName];
    }
    if (hpItem.layout) {
        [viewLayout addObject:hpItem.layout];
    }
    
    //More view
    DataInfo *dataInfo = [AppsProjectInfoParser parseDataInfo];
    if (dataInfo.moreLayout) {
        [viewName addObject:@"More"];
        if (dataInfo.moreLayout) {
            [viewLayout addObject:dataInfo.moreLayout];
        }
    }
    
    for (int i = 2; i < [dInfo.dataList count]; i++) {
        TabDataListItem *item = [dInfo.dataList objectAtIndex:i];
        if (item.sysTabName) {
            [viewName addObject:item.sysTabName];
        }
        if (item.layout) {
            [viewLayout addObject:item.layout];
        }
    }
    
    NSString *str = @"";
    reserveTabsArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < [viewName count]; i++) {
        NSString *tabName = [viewName objectAtIndex:i];
        NSString *layoutName = [viewLayout objectAtIndex:i];
        layoutName = [layoutName stringByReplacingOccurrencesOfRegex:@"l" withString:@"L"];
        //        if (![tabName isEqualToString:@"Enquiry-Appointment-Form"]) {
        //            tabName = [tabName stringByReplacingOccurrencesOfRegex:@"-" withString:@"_"];
        //        }
        tabName = [tabName stringByReplacingOccurrencesOfRegex:@"-" withString:@"_"];//服务器以"-"命名，本地以"_"命名
        
        str = [str stringByAppendingFormat:@"%@ - %@ \n",tabName,layoutName];
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] init];
        [_dict setObject:tabName forKey:@"tabName"];
        [_dict setObject:layoutName forKey:@"layout"];
        if (![self isValueExist:_dict inArray:reserveTabsArray]) {
            //避免重复值
            [reserveTabsArray addObject:_dict];
        }
    }
    
    NSMutableDictionary *baseDict = [[NSMutableDictionary alloc] init];
    for (int i = 0; i <  [reserveTabsArray count]; i++) {
        NSDictionary *_dict = [reserveTabsArray objectAtIndex:i];
        [baseDict setObject:@"base" forKey:[_dict objectForKey:@"tabName"]];
        [baseDict setObject:@"Base" forKey:[_dict objectForKey:@"tabName"]];
    }
    
    NSEnumerator *baseEnm = [baseDict keyEnumerator];
    for (NSString *sKey in baseEnm) {
        NSMutableDictionary *_dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[baseDict objectForKey:sKey],@"layout",sKey,@"tabName", nil];
        [reserveTabsArray addObject:_dict];
    }
    
    
}

#pragma mark - 第3步--执文件
-(void)pickFiles {
    NSLog(@">>>>>>>>>>>>>>>>>>>IOS: Picking files,it takes about 1~2 min... <<<<<<<<<<<<<<<<<<<\n");
     PathParser *pp = [PathParser sharePathParser];
    
    NSString *projectPath = pp.outIosProjectPath;//@"/Users/Vescky/Documents/Test/AutoCompilerWorkSpace/NineAsk";
    TabItemDictionary *ti = [[TabItemDictionary alloc] init];
    //执文件
    
    
    NSMutableArray *delFileList = [ti getConfigFromFileList:reserveTabsArray];
//    NSMutableArray *finalList = [[NSMutableArray alloc] init];
//    for (int i = 0; i< delFileList.count  ; i++) {
//        NSString *fName = [delFileList objectAtIndex:i];
//        if ([[fName lowercaseString] stringByMatching:@"Lynx"]) {
//            
//        }
//    }
    //    [Modify_pbxproj deleteFilesWithArray:delFileList usingFastMode:YES projectPath:projectPath];
    //    [Modify_pbxproj deleteFilesExceptArray:reserveTabsArray fileList:delFileList projectPath:projectPath];
    NSLog(@"delete these files:\n%@",delFileList);
    [Modify_pbxproj deleteFilesExceptArray:reserveTabsArray fileList:delFileList usingFastMode:NO projectPath:projectPath];
}

#pragma mark - 第4步--修改程序信息
-(bool)ModifyAppInfoWithAppCNName:(NSString*)appName AppENName:(NSString*)bundleName deploymentSDKVersion:(NSString*)sdkVersion AppVersion:(NSString*)appVersion  ProjectPath:(NSString*)projectPath {
    NSLog(@">>>>>>>>>>>>>>>>>>>IOS: Modifying app info,it takes about 10s... <<<<<<<<<<<<<<<<<<<<\n");
    
//    PathParser *pp = [PathParser sharePathParser];
    
    if (!projectPath) {
        return NO;
    }
    
    //修改app名
    NSLog(@"modify IOS app name...\n");
    [Modify_pbxproj modifyAppName:appName projectPath:projectPath];
    [Modify_pbxproj modifyProductName:appName projectPath:projectPath];

//    //修改bundleID
//    NSLog(@"modify IOS app ID...\n");
//    [Modify_pbxproj modifyBundleID:[NSString stringWithFormat:@"%@.%@",pp.appBundleIdHeadString,bundleName] projectPath:projectPath];
    
    //修改部署SDK版本
    [Modify_pbxproj modifyDeploymentVersion:sdkVersion projectPath:projectPath];

    //修改appVersion
    [Modify_pbxproj modifyAppVersion:appVersion projectPath:projectPath];
    
    return YES;
}

//修改ip地址,tomcat,googlemap配置以及xmpp
- (bool)ModifyServerIP:(NSString*)ipAddress withMode:(NSString*)_mode {
    if (!ipAddress || ipAddress.length <= 0) {
        return NO;
    }
    PathParser *pp = [PathParser sharePathParser];
    
    NSString *fPath = [NSString stringWithFormat:@"%@/%@/AppDelegate.m",pp.outIosProjectPath,pp.templateProjectName];
    NSString *appDelegateString = [[NSString alloc] initWithContentsOfFile:fPath encoding:NSUTF8StringEncoding error:nil];
    appDelegateString = [appDelegateString stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERIP" withString:ipAddress];
    
    [appDelegateString writeToFile:fPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
#pragma - 修改测试警告信息
    NSString *constancePath = [NSString stringWithFormat:@"%@/%@/Classes/Apps123_Foundation/Static/AppsConstants.h",pp.outIosProjectPath,pp.templateProjectName];
    NSString *conContent = [NSString stringWithContentsOfFile:constancePath encoding:NSUTF8StringEncoding error:nil];
    
    int bMode = [_mode intValue] % 100;
    //判断app种类
    if (bMode % 3 == 1) {//bMode == 1 || bMode == 4 publish
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"false"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"false"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"prod"];
    }
    else if (bMode % 3 == 2) {//bMode == 2 || bMode == 5 preview
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"true"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"true"];
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"wip"];
    }
    else {
        if ([ipAddress isEqualToString:pp.wipServerIP]) {
            //preview
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"true"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"true"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"wip"];
        }
        else {
            //publish
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_3MINTEST" withString:@"false"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERTEST" withString:@"false"];
            conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_LYNXFORUMDB" withString:@"prod"];
        }
    }
    
    //修改googlemap配置
    DataInfo *dInfo = [AppsProjectInfoParser parseDataInfo];
    if (dInfo.mapType == GoogleMap) {
        conContent = [conContent stringByReplacingOccurrencesOfString:@"XAPPS123X_GOOGLEMAP" withString:@"Using_GoogleMapKit"];
    }
    
    [conContent writeToFile:constancePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

- (bool)ModifyXmppIp:(NSString*)xmppIp {
    if (!xmppIp || xmppIp.length <= 0) {
        return NO;
    }
    PathParser *pp = [PathParser sharePathParser];
    
    NSString *fPath = [NSString stringWithFormat:@"%@/%@/AppDelegate.m",pp.outIosProjectPath,pp.templateProjectName];
    NSString *appDelegateString = [[NSString alloc] initWithContentsOfFile:fPath encoding:NSUTF8StringEncoding error:nil];
    appDelegateString = [appDelegateString stringByReplacingOccurrencesOfString:@"XAPPS123X_SERVERXMPPIP" withString:xmppIp];
    [appDelegateString writeToFile:fPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

#pragma mark - 第5步--compile 
- (void)compileWithLogsFiles:(bool)isLogFileOn appName:(NSString*)appName {
    NSLog(@">>>>>>>>>>>>>>>>>>>IOS: Compiling project,it takes about 3mins... <<<<<<<<<<<<<<<<<<<<<\n");
    
    PathParser *pp = [PathParser sharePathParser];
    
    NSString *projectPath = pp.outIosProjectPath;
    NSString *buildScriptPath = [NSString stringWithFormat:@"%@/XcodeBuildScript.sh",pp.scriptFilesPath];
    
    //去空格处理
    buildScriptPath = [buildScriptPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    projectPath = [projectPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    
    NSString *buildCommand = [NSString stringWithFormat:@"%@ %@ %s %@",buildScriptPath,projectPath,"1",pp.latestSdkVersion];
    
    
    NSString *ipaScriptPath = [NSString stringWithFormat:@"%@/ipaScript.sh",pp.scriptFilesPath];
    NSString *appPath = [projectPath stringByAppendingString:@"/build/Debug-iphoneos"];
    NSString *ipaPath = pp.outputAppPath;
    
//    NSString *pId = proInfo.projectID;
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:appPath]) {
        appPath = [projectPath stringByAppendingString:@"/build/Release-iphoneos"];
    }
    
    //去空格处理
    ipaScriptPath = [ipaScriptPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    appPath = [appPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    appName = [appName stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    ipaPath = [ipaPath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
    NSString *ipaCommand = [NSString stringWithFormat:@"%@ %@ %@ %@",ipaScriptPath,appPath,appName,ipaPath];
    
    if (isLogFileOn) {
        NSString *buildLogPath = [pp.outputLogFilesPath stringByAppendingPathComponent:@"IOS_CompileLog.log"];
        mysystem2([buildCommand UTF8String], (char*)[buildLogPath UTF8String]);
    
        //去除应用名称的空格
        [self deleteSpaceInAppName:appPath];
        
//        NSString *packageIpaLog = [pp.outputLogFilesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"ipaLog_%@.log",pId]];
//        mysystem2([ipaCommand UTF8String], (char*)[packageIpaLog UTF8String]);
        system([ipaCommand UTF8String]);
    }
    else {
        system([buildCommand UTF8String]);
        
        //去除应用名称的空格
        [self deleteSpaceInAppName:appPath];
        
        system([ipaCommand UTF8String]);
    }
    NSLog(@">>>>>>>>>>>>>> IOS: Compile complete <<<<<<<<<<<<<<\n");
    
    if ([delegate respondsToSelector:@selector(iosAutoRunDone)]) {
        [delegate iosAutoRunDone];
    }
}


- (bool)isValueExist:(id)_object inArray:(NSArray*)_array {
    for (int i = 0; i < [_array count]; i++) {
        if ([_object isEqualTo:[_array objectAtIndex:i]]) {
            return YES;
        }
    }
    return NO;
}

- (void)deleteSpaceInAppName:(NSString*)productPath {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *fileList = [[FileOperator shareFileOperator] getListOfPath:productPath isDir:YES];
    for (int i = 0; i < [fileList count]; i++) {
        NSString *fileName = [fileList objectAtIndex:i];
        if ([[fileName pathExtension] isEqualToString:@"app"]) {
            NSString *newFileName = [fileName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
            if (![fileName isEqualToString:newFileName]) {
               [fm moveItemAtPath:[productPath stringByAppendingPathComponent:fileName]  toPath:[productPath stringByAppendingPathComponent:newFileName] error:nil];
            }
        }
    }
}

#pragma mark - ImageEngineDelegate
- (void)AppsImageEngineLoadImageComplete:(NSImage*)_image {
    NSLog(@"IOS: load image done\n");
//    [NSThread sleepForTimeInterval:5.0];
//    [self compileWithLogsFiles:NO];
    isLoadingIconsComplete = YES;
}

int mysystem2(const char* cmdstring,char* tmpfile)
{
    char cmd_string[1024];
    
    //    tmpnam(tmpfile);
    FILE *file = fopen(tmpfile, "a+");
    if (!file) {
        return -1;
    }
    fclose(file);
    
    sprintf(cmd_string, "%s > %s", cmdstring, tmpfile);
    
    return system(cmd_string);
}

- (void)test {
    [self deleteSpaceInAppName:@"/temp/k-apps&9apps/3kapps/3Tests/Test5140/out/ios/AppsTemplate/build/Release-iphoneos"];
}

- (void)loadIOSIconsUsingGCDWithImageUrl:(NSString*)url projectPath:(NSString*)pPath {
    iosIconDone = 0;
    
    if (!url || url.length <= 0) {
        return;
    }
//    
//    NSString *ext = [url pathExtension];
//    url = [url stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",ext] withString:@""];//去掉尾部
    
    __block NSString *str_57x57 = [url stringByAppendingString:@"_r57x57.png"];
    __block NSString *str_114x114 = [url stringByAppendingString:@"_r114x114.png"];
    __block NSString *str_120x120 = [url stringByAppendingString:@"_r120x120.png"];
    __block NSString *str_512x512 = [url stringByAppendingString:@"_r512x512.png"];
    
    dispatch_queue_t queue1 = dispatch_queue_create("DownloadIcons", NULL);
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str_57x57]];
        result = [[NSImage alloc] initWithData:data];
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"icon.png"]];
        iosIconDone++;
        NSLog(@"icon for 57x57 complete! No.%d\n",iosIconDone);
        if (iosIconDone >= TOTAL_ICONS) {
            NSLog(@"IOS: load image done\n");
            isLoadingIconsComplete = YES;
        }
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str_114x114]];
        result = [[NSImage alloc] initWithData:data];
        
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"icon@2x.png"]];
        iosIconDone++;
        NSLog(@"icon for 114x114 complete! No.%d\n",iosIconDone);
        if (iosIconDone >= TOTAL_ICONS) {
            NSLog(@"IOS: load image done\n");
            isLoadingIconsComplete = YES;
        }
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str_120x120]];
        result = [[NSImage alloc] initWithData:data];
        
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"icon_ios7.png"]];
        iosIconDone++;
        NSLog(@"icon for 120x120 complete! No.%d\n",iosIconDone);
        if (iosIconDone >= TOTAL_ICONS) {
            NSLog(@"IOS: load image done\n");
            isLoadingIconsComplete = YES;
        }
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str_512x512]];
        result = [[NSImage alloc] initWithData:data];
        
        [[AppsImageEngine sharedEngine] saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"iTunesArtwork"]];
        iosIconDone++;
        NSLog(@"icon for 512x512 complete! No.%d\n",iosIconDone);
        if (iosIconDone >= TOTAL_ICONS) {
            NSLog(@"IOS: load image done\n");
            isLoadingIconsComplete = YES;
        }
    });
}


- (bool)saveIconWithLocalIconImage:(NSImage*)bigImage {
    
    if (!bigImage) {
        return NO;
    }
    
    NSImage *sIconImage = [bigImage scaleToSize:CGSizeMake(57.0, 57.0)];
    NSImage *dIconImage = [bigImage scaleToSize:CGSizeMake(114.0, 114.0)];
    
    PathParser *pp = [PathParser sharePathParser];
    NSString *resourcesPath = [NSString stringWithFormat:@"%@/%@/Resources",pp.outIosProjectPath,pp.templateProjectName];
    NSString *sIconPath = [resourcesPath stringByAppendingPathComponent:@"icon.png"];
    NSString *dIconPath = [resourcesPath stringByAppendingPathComponent:@"icon@2x.png"];
    NSString *oIconPath = [resourcesPath stringByAppendingPathComponent:@"iTunesArtwork"];

    [[AppsImageEngine sharedEngine] saveImage:sIconImage saveType:NSPNGFileType properties:nil ToTarget:sIconPath];
    [[AppsImageEngine sharedEngine] saveImage:dIconImage saveType:NSPNGFileType properties:nil ToTarget:dIconPath];
    [[AppsImageEngine sharedEngine] saveImage:bigImage saveType:NSPNGFileType properties:nil ToTarget:oIconPath];
    
    return YES;
}

- (NSString*)getProfilePath:(NSString*)appType {
    PathParser *pp = [PathParser sharePathParser];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    //证书总类，InHouse还是AcHoc
    NSString *idExtention = @"achoc.mobileprovision";
    if ([appType isEqualToString:@"preview"]) {
        idExtention = @"inhouse.mobileprovision";
    }
    
    NSString *certsPathForBundleResources = [NSString stringWithFormat:@"%@/pushcerts",pp.incomeBundlePath];
    if ([fm fileExistsAtPath:certsPathForBundleResources]) {
        NSString *tmpPath = [pp.outIosProjectPath stringByDeletingLastPathComponent];
        NSString *projectCertsPath = [tmpPath stringByAppendingPathComponent:@"pushcerts"];
        [fm moveItemAtPath:certsPathForBundleResources toPath:projectCertsPath error:nil];
        NSMutableArray *certsList = [[FileOperator shareFileOperator] getListOfPath:projectCertsPath isDir:NO];
        if ([certsList count] > 1) {
            for (int i = 0; i < [certsList count]; i++) {
                NSString *tmpFileName = [certsList objectAtIndex:i];
                tmpFileName = [tmpFileName lowercaseString];
                //存在证书
                if ([tmpFileName stringByMatching:idExtention]) {
                    return [projectCertsPath stringByAppendingPathComponent:tmpFileName];
                }
            }
        }
    }
    return nil;
}



@end
